package com.yanxi.yxregiserve.web.grpc.impl;

import com.alibaba.fastjson.JSON;
import com.yanxi.yxregiserve.web.common.constant.GrpcConstants;
import com.yanxi.yxregiserve.web.domin.system.ConfigData;
import com.yanxi.yxregiserve.web.grpc.pullConfigService.PullConfigRequest;
import com.yanxi.yxregiserve.web.grpc.pullConfigService.PullConfigResponse;
import com.yanxi.yxregiserve.web.grpc.pullConfigService.PullConfigServiceGrpc;
import com.yanxi.yxregiserve.web.service.system.ConfigDataService;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;


@GrpcService
public class PullConfigServiceImpl extends PullConfigServiceGrpc.PullConfigServiceImplBase {

    @Autowired
    private ConfigDataService configDataService;

    private static final Logger logger = Logger.getLogger(PullConfigServiceImpl.class.getName());

    @Override
    public void getConfigByTag(PullConfigRequest request, StreamObserver<PullConfigResponse> responseStreamObserver) {

        /**
         * 拿到请求参数
         */
        String tag = request.getStr();

        /**
         * 条件查询 配置 Map
         */
        List<ConfigData> configData = configDataService.selectTList(ConfigData.builder().tag(tag).build());

        /**
         * 转化为map
         */
        Map<String, String> configDataMap = configData.stream()
                .collect(Collectors.toMap(ConfigData::getKey, ConfigData::getValue));

        /**
         * 格式转化
         */
        String configDataJson = JSON.toJSONString(configDataMap);

        /**
         * 发送
         */
        responseStreamObserver.onNext(PullConfigResponse.newBuilder()
                .setData(configDataJson)
                .setStatus(GrpcConstants.RPC_SUCCESS_CODE)
                .setMsg(GrpcConstants.RPC_SUCCESS)
                .build());

        responseStreamObserver.onCompleted();
    }

}
